import { Message } from 'element-ui'
import axios from 'axios'
import store from '@/store'
import router from '@/router'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
// 后端自定义了一个标识当前接口成功失败的字段，叫做success，而不是通过http状态码是否为2xx-3xx来标识接口是否成功
service.interceptors.response.use(
  response => {
    const { data, success, message } = response.data
    if (success) {
      return data
    } else {
      Message.warning(message)
      return Promise.reject(message)
    }
  },
  error => {
    console.dir(error)
    if (error.response.status === 401) {
      // 1.清空数据
      store.commit('user/removeUserInfo')
      // 2.跳转页面
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
